package com.tarena.lbs.user.service.impl;

import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.common.utils.HttpContextUtils;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.api.pojo.dto.UserDto;
import com.tarena.lbs.user.dao.repository.UserGroupRepository;
import com.tarena.lbs.user.dao.repository.UserRepository;
import com.tarena.lbs.user.dao.repository.UserTagsRepository;
import com.tarena.lbs.user.pojo.param.UserParam;
import com.tarena.lbs.user.pojo.param.UserTagsParam;
import com.tarena.lbs.user.pojo.po.UserGroupPO;
import com.tarena.lbs.user.pojo.po.UserPO;
import com.tarena.lbs.user.pojo.po.UserTagsPO;
import com.tarena.lbs.user.pojo.vo.UserGroupVO;
import com.tarena.lbs.user.pojo.vo.UserVO;
import com.tarena.lbs.user.service.UserService;
import com.tarena.lbs.user.utils.RandomUserName;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final UserTagsRepository userTagsRepository;
    private final UserGroupRepository userGroupRepository;


    @Override
    public void register(UserParam param) throws BusinessException {
        String phone = param.getPhone();
        Long count = userRepository.countUserByPhone(phone);
        Asserts.isTrue(count>0,new BusinessException("-2","手机号已经存在"));
        //2.封装数据
        UserPO poParam = assembleUserPO(param);
        //3.直接写入数据库
        userRepository.save(poParam);
    }
    @Override
    public void save(UserParam param) {
       UserPO po = new UserPO();
       BeanUtils.copyProperties(param,po);
       userRepository.update(po);
    }

    @Override
    public UserVO detail() throws BusinessException {
        //1.解析jwt 拿到userPrinciple
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        Integer userId = userPrinciple.getId();
        //2.仓储层查询唯一的po
        UserPO po = userRepository.getById(userId);
        Asserts.isTrue(po==null,new BusinessException("-2","用户信息不存在"));
        //3.转化vo
        UserVO vo=new UserVO();
        BeanUtils.copyProperties(po,vo);
        return vo;
    }
    @Override
    public void bindUserTags(UserTagsParam param) throws BusinessException{
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        String[] tagIds = param.getTagIds().split(",");
        for (String tagId : tagIds) {
            UserTagsPO userTagsPO=new UserTagsPO();
            userTagsPO.setTagId(Integer.parseInt(tagId));
            userTagsPO.setUserId(userPrinciple.getId());
            userTagsRepository.save(userTagsPO);
        }
    }

    private UserPO assembleUserPO(UserParam param) {
        UserPO po=new UserPO();
        BeanUtils.copyProperties(param,po);
        //补充必要数据 用户状态 0表示没有绑定标签 1 表示绑定了标签
        po.setStatus(0);
        //用户昵称 注册时候 不是用户填写的 为了快速注册 我们随机生成一个
        String randomName = RandomUserName.createRandomName();//老 大 小  张王李赵
        po.setNickName(randomName);
        po.setUserName(randomName);
        //注册时间
        po.setRegTime(new Date());
        return po;
    }

    public UserDto detail(Integer userId) {
        UserPO userPO = userRepository.getById(userId);
        UserDto userDto = null;
        if (userPO != null){
            userDto = new UserDto();
            BeanUtils.copyProperties(userPO, userDto);
        }
        return userDto;

    }

    public List<Integer> getGroupIds(Integer userId, Integer businessId) {
        //获取用户身上的标签ids
        List<UserTagsPO> tags = userTagsRepository.getUserTagsByUserId(userId);
        List<Integer> tagIds = new ArrayList<>();
        tags.forEach(tag -> {
            tagIds.add(tag.getTagId());
        });
        //获取该商家下所有的人群
        List<UserGroupVO> groups = userGroupRepository.listUserGroups(businessId);
        //遍历人群，判断每个人群的用户标签ids与用户身上的标签ids是否有交集
        List<Integer> resultGroupIds = new ArrayList<>();
        groups.forEach(group -> {
            //将String[]转为List<Integer>
            List<Integer> groupTagIds = Arrays.stream(group.getTagIds().split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            //判断是否有交集
            List<Integer> intersection = new ArrayList<>(tagIds);
            intersection.retainAll(groupTagIds);
            if (!intersection.isEmpty()){//不为空，有交集
                resultGroupIds.add(group.getId());
            }
        });
        return resultGroupIds;
    }
}
